package com.zmn.plat.admin.controller.msg.conf;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.constant.StatusConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.mcc.cas.model.LoginStaff;
import com.zmn.plat.model.entity.msg.conf.MsgConf;
import com.zmn.plat.model.entity.msg.conf.MsgConfQuery;
import com.zmn.plat.model.entity.msg.receive.position.conf.MsgReceivePositionConf;
import com.zmn.plat.model.entity.msg.receive.role.conf.MsgReceiveRoleConf;
import com.zmn.plat.model.entity.msg.receive.staff.conf.MsgReceiveStaffConf;
import com.zmn.plat.model.entity.msg.receive.staff.conf.MsgReceiveStaffConfQuery;

/**
 * 消息配置表
 *
 * @author linfeng
 * @since 2020-05-18 14:50:14
 */
@RestController
@RequestMapping("/msg/conf/")
public class MsgConfModifyController extends MsgConfBaseController {

    /**
     * 新增修改
     *
     * @param msgConf
     * @author linfeng
     * @since 2020-05-18 14:50:14
     */
    @RequestMapping(value = "addEdit")
    @RequiresPermissions("/msg/conf/addEdit.action")
    public ResponseDTO addEdit(HttpServletRequest request, @RequestBody MsgConf msgConf) {
        Date now = DateUtil.getNow();
        String opertor = getMcStaffRealName();
        Integer msgId = msgConf.getMsgId();

        MsgConfQuery msgConfQuery = new MsgConfQuery();
        msgConfQuery.setName(msgConf.getName());
        List<MsgConf> msgConfs = msgConfService.listByQuery(msgConfQuery);

        try {
            if (msgId == null || msgId == 0) {
                if (msgConfs != null && msgConfs.size() > 0) {
                    return ResponseDTO.fail(String.format("已经存在消息名称为：[%s]的数据！", msgConf.getName()));
                }
                msgConf.setCreater(opertor);
                msgConf.setCreateTime(now);
                msgConf.setUpdater(opertor);
                msgConf.setUpdateTime(now);
                msgConf.setStatus(GlobalConsts.NO);
                if (msgConf.getSort() == null) {
                    Integer sort = msgConfService.findMaxSort();
                    sort = sort == null ? 1 : sort + 1;
                    msgConf.setSort(sort);
                }
                msgConfService.insert(msgConf);
            } else {
                if (msgConfs != null && msgConfs.size() > 0) {
                    if (msgConfs.size() > 1 || !Objects.equals(msgConfs.get(0).getMsgId(), msgConf.getMsgId())) {
                        return ResponseDTO.fail(String.format("已经存在消息名称为：[%s]的数据！", msgConf.getName()));
                    }
                }
                msgConf.setUpdater(opertor);
                msgConf.setUpdateTime(now);
                msgConfService.updateByKey(msgConf);
            }

            return ResponseDTO.success(StatusConsts.STATUS_SUCCESS, "操作成功！");
        } catch (Exception ex) {
            logger.error("新增/修改消息配置表失败：msgConf:{}", msgConf, ex);
            return ResponseDTO.fail("操作失败");
        }
    }

    @RequestMapping(value = "receive/position/save")
    @RequiresPermissions("/msg/conf/receive/position/save.action")
    public ResponseDTO savePosition(@RequestParam(value = "ids") List<Integer> ids,
        @RequestParam(value = "msgId", defaultValue = "0") int msgId) {
        if (msgId == 0) {
            return ResponseDTO.fail("参数异常");
        }
        LoginStaff mcStaff = getMcStaff();

        // 删除该消息对应的所有接收信息岗位数据
        msgReceivePositionConfService.deleteByMsgId(msgId);

        List<MsgReceivePositionConf> list = ids.stream().map(deptId -> {
            MsgReceivePositionConf msgReceivePositionConf = new MsgReceivePositionConf() {
                {
                    setOrgId(Integer.valueOf(deptId));
                    setMsgId(msgId);
                    setCreater(mcStaff.getRealName());
                    setCreateTime(DateUtil.getNow());
                    setUpdater(mcStaff.getRealName());
                    setUpdateTime(DateUtil.getNow());
                }
            };
            return msgReceivePositionConf;
        }).collect(Collectors.toList());
        msgReceivePositionConfService.insertBatch(list);

        return ResponseDTO.success(StatusConsts.STATUS_SUCCESS, "保存成功!");
    }

    @RequestMapping(value = "receive/role/save")
    @RequiresPermissions("/msg/conf/receive/role/save.action")
    public ResponseDTO saveRole(@RequestParam(value = "ids") List<String> ids,
        @RequestParam(value = "msgId", defaultValue = "0") int msgId) {
        if (msgId == 0) {
            return ResponseDTO.fail("参数异常");
        }
        LoginStaff mcStaff = getMcStaff();

        // 删除该消息对应的所有接收角色岗位数据
        msgReceiveRoleConfService.deleteByMsgId(msgId);

        List<MsgReceiveRoleConf> list = ids.stream().map(roleId -> {
            MsgReceiveRoleConf msgReceivePositionConf = new MsgReceiveRoleConf() {
                {
                    setRoleId(Integer.valueOf(roleId));
                    setMsgId(msgId);
                    setCreater(mcStaff.getRealName());
                    setCreateTime(DateUtil.getNow());
                    setUpdater(mcStaff.getRealName());
                    setUpdateTime(DateUtil.getNow());
                }
            };
            return msgReceivePositionConf;
        }).collect(Collectors.toList());
        msgReceiveRoleConfService.insertBatch(list);

        return ResponseDTO.success(StatusConsts.STATUS_SUCCESS, "保存成功!");
    }

    /**
     * 新增消息接收员工
     *
     * @param msgReceiveStaffConf
     * @author linfeng
     * @since 2020-05-19 11:41:45
     */
    @RequestMapping(value = "/receive/staff/addEdit")
    @RequiresPermissions("/msg/conf/receive/staff/addEdit.action")
    public ResponseDTO addEdit(HttpServletRequest request, @RequestBody MsgReceiveStaffConf msgReceiveStaffConf) {
        Date now = DateUtil.getNow();
        String opertor = getMcStaffRealName();

        MsgReceiveStaffConfQuery msgReceiveStaffConfQuery = new MsgReceiveStaffConfQuery();
        msgReceiveStaffConfQuery.setMsgId(msgReceiveStaffConf.getMsgId());
        msgReceiveStaffConfQuery.setStaffId(msgReceiveStaffConf.getStaffId());
        List<MsgReceiveStaffConf> msgReceiveStaffConfs = msgReceiveStaffConfService.listByQuery(msgReceiveStaffConfQuery);

        try {
            if (msgReceiveStaffConfs != null && msgReceiveStaffConfs.size() > 0) {
                return ResponseDTO.fail("已经存在该员工，请勿重复添加！");
            }
            msgReceiveStaffConf.setCreater(opertor);
            msgReceiveStaffConf.setCreateTime(now);
            msgReceiveStaffConf.setUpdater(opertor);
            msgReceiveStaffConf.setUpdateTime(now);
            msgReceiveStaffConfService.insert(msgReceiveStaffConf);

            return ResponseDTO.success(StatusConsts.STATUS_SUCCESS, "操作成功！");
        } catch (Exception ex) {
            logger.error("新增接收信息员工失败：msgReceiveStaffConf:{}", msgReceiveStaffConf, ex);
            return ResponseDTO.fail("操作失败");
        }
    }

    @RequestMapping(value = "receive/staff/delete")
    @RequiresPermissions("/msg/conf/receive/staff/delete.action")
    public ResponseDTO deleteStaff(@RequestParam(value = "id") Integer id) {
        if (id == 0) {
            return ResponseDTO.fail("参数异常");
        }

        msgReceiveStaffConfService.deleteByKey(id);

        return ResponseDTO.success(StatusConsts.STATUS_SUCCESS, "删除成功!");
    }

    /**
     * 修改排序
     *
     * @param id
     * @param sort
     * @author linfeng
     * @since 2020-05-18 14:50:14
     */
    @RequestMapping(value = "updateSort")
    @RequiresPermissions("/msg/conf/list.action")
    public ResponseDTO updateSort(HttpServletRequest request, @RequestParam(value = "id", defaultValue = "0") Integer id,
        @RequestParam(value = "sort", defaultValue = "0") Integer sort) {

        if (id == 0) {
            return ResponseDTO.fail("请选择要更改排序的数据！");
        }
        if (sort == 0) {
            return ResponseDTO.fail("请设置排序值！");
        }

        msgConfService.updateSortByKey(id, sort, getMcStaffRealName());
        return ResponseDTO.success(StatusConsts.STATUS_SUCCESS, GlobalConsts.SUCCESS_MSG);
    }

    /**
     * 修改状态
     *
     * @param ids
     * @param status
     * @author linfeng
     * @since 2020-05-18 14:50:14
     */
    @RequestMapping(value = "updateStatus")
    @RequiresPermissions("/msg/conf/updateStatus.action")
    public ResponseDTO updateStatus(HttpServletRequest request, @RequestParam(value = "ids", defaultValue = "") String ids,
        @RequestParam(value = "status", defaultValue = "0") Integer status) {
        if (StringUtil.isBlank(ids)) {
            return ResponseDTO.fail("请选择要更改状态的数据！");
        }
        if (status == 0) {
            return ResponseDTO.fail("请设置状态！");
        }

        List<Integer> arrayIds = StringUtil.convertStrsToList(ids);

        msgConfService.updateStatusBatchByKey(arrayIds, status, getMcStaffRealName());
        return ResponseDTO.success(StatusConsts.STATUS_SUCCESS, GlobalConsts.SUCCESS_MSG);
    }
}
